<script setup lang="ts">

import { ref, onMounted, computed } from "vue";
import Galleria from 'primevue/galleria';
import { useUserStore } from "@/stores/modules/user";
import IconField from 'primevue/iconfield';
import InputIcon from 'primevue/inputicon';
import Toolbar from 'primevue/toolbar';
import FileUpload from 'primevue/fileupload';
import DataTable from 'primevue/datatable';
import Column from 'primevue/column';
import ColumnGroup from 'primevue/columngroup';   // optional
import Row from 'primevue/row';                   // optional
import { FilterMatchMode } from 'primevue/api';
import { useToast } from 'primevue/usetoast';
import { addExamInfoApi, getExamInfo } from "@/api/exam/index";
import Steps from 'primevue/steps';
import RadioButton from 'primevue/radiobutton';
import { useConfirm } from "primevue/useconfirm";
import type { number } from "yup";



const confirm = useConfirm();
const userStore = useUserStore();
const userInfo: any = computed(() => userStore.userInfo);

// 考试状态
// const examInfo = ref('');

// 新建考试弹框
const examAddParams = ref({
    info: "",
    status: 1,
});



// 考试状态
const ingredient = ref('');

const items = ref([
    {
        label: '创建考试'
    },
    {
        label: '上传试卷'
    },
    {
        label: '保存'
    }
]);

const toast = useToast();

const deleteConfirm = () => {
    confirm.require({
        message: '你确定要删除这个记录?',
        header: '删除提醒',
        icon: 'pi pi-info-circle',
        rejectLabel: '取消',
        acceptLabel: '删除',
        rejectClass: 'p-button-secondary p-button-outlined',
        acceptClass: 'p-button-danger',
        accept: () => {
            toast.add({ severity: 'success', summary: '成功', detail: '删除考试成功', life: 3000 })
        },
        // reject: () => {
        //     toast.add({ severity: 'error', summary: '失败', detail: '删除考试失败', life: 3000 });
        // }
    });
};


const examInfosData = ref([{
    id: 1,
    info: "2024七校联考模拟",
    status: 1,
    date: "2024-2-3"
}]);



onMounted(() => {
    getExamInfo().then((res: any) => {
        examInfosData.value = res.data;
    });
});



/**
 * 新建考试
 */
const onSave = () => {

    addExamInfoApi({ ...examAddParams.value }).then(res => {
        toast.add({ severity: 'success', summary: '成功', detail: '新增考试成功', life: 3000 })
        addExamInfoDialog.value = false
        // 刷新考试列表             
        getExamInfo().then((res) => {
            examInfosData.value = res.data;
        });
    }).catch(err => {
    })
};


const responsiveOptions = ref([
    {
        breakpoint: '1300px',
        numVisible: 4
    },
    {
        breakpoint: '575px',
        numVisible: 1
    }
]);

const dt = ref();
// 新建考试弹框
const addExamInfoDialog = ref(false);

const deleteExamInfoDialog = ref(false);
const deleteProductsDialog = ref(false);
const product = ref({});
const selectedProducts = ref();
const filters = ref({
    'global': { value: null, matchMode: FilterMatchMode.CONTAINS },
});
const submitted = ref(false);
const statuses = ref([
    { label: 'INSTOCK', value: 'instock' },
    { label: 'LOWSTOCK', value: 'lowstock' },
    { label: 'OUTOFSTOCK', value: 'outofstock' }
]);

// const formatCurrency = (value) => {
//     if(value)
//         return value.toLocaleString('en-US', {style: 'currency', currency: 'USD'});
//     return;
// };
const openNew = () => {
    // product.value = {};
    // submitted.value = false;
        // 清空表单数据
        examAddParams.value = {
        info: "",
        status: 1,
    };
    addExamInfoDialog.value = true;
};
const hideDialog = () => {
    addExamInfoDialog.value = false;
    submitted.value = false;
};
const saveExamInfo = () => {
    submitted.value = true;

    // if (product.value.name.trim()) {
    //     if (product.value.id) {
    //         product.value.inventoryStatus = product.value.inventoryStatus.value ? product.value.inventoryStatus.value : product.value.inventoryStatus;
    //         products.value[findIndexById(product.value.id)] = product.value;
    //         toast.add({severity:'success', summary: 'Successful', detail: 'Product Updated', life: 3000});
    //     }
    //     else {
    //         product.value.id = createId();
    //         product.value.code = createId();
    //         product.value.image = 'product-placeholder.svg';
    //         product.value.inventoryStatus = product.value.inventoryStatus ? product.value.inventoryStatus.value : 'INSTOCK';
    //         products.value.push(product.value);
    //         toast.add({severity:'success', summary: 'Successful', detail: 'Product Created', life: 3000});
    //     }

    //     productDialog.value = false;
    //     product.value = {};
    // }
};
const addExamInfo = (prod: any) => {
    examAddParams.value = { ...prod };
    addExamInfoDialog.value = true;
    console.log(prod);

};



// const confirmDeleteProduct = (prod:any) => {
//     product.value = prod;
//     deleteExamInfoDialog.value = true;
// };


const deleteExamInfo = () => {
    // products.value = products.value.filter(val => val.id !== product.value.id);
    // deleteProductDialog.value = false;
    // product.value = {};
    // toast.add({severity:'success', summary: 'Successful', detail: 'Product Deleted', life: 3000});
};
// const findIndexById = (id) => {
//     let index = -1;
//     for (let i = 0; i < products.value.length; i++) {
//         if (products.value[i].id === id) {
//             index = i;
//             break;
//         }
//     }

//     return index;
// };
// const createId = () => {
//     let id = '';
//     var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
//     for (var i = 0; i < 5; i++) {
//         id += chars.charAt(Math.floor(Math.random() * chars.length));
//     }
//     return id;
// }
const exportCSV = (e: any) => {
    dt.value.exportCSV();
    console.log(e);

};
const confirmDeleteSelected = () => {
    deleteProductsDialog.value = true;
};
const deleteSelectedProducts = () => {
    // products.value = products.value.filter(val => !selectedProducts.value.includes(val));
    // deleteProductsDialog.value = false;
    // selectedProducts.value = null;
    toast.add({ severity: 'success', summary: 'Successful', detail: 'Products Deleted', life: 3000 });
};



// 状态标签
const getStatusLabel = (status: number) => {
    switch (status) {
        case 0:
            return 'success';

        case 1:
            return 'warning';

        default:
            return 'danger';
    }
};




const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    return `${year}-${month}-${day}`;
};
</script>

<template>
    <div class="card mb-3">
        <Steps :model="items" />
    </div>
    <div>
        <Toolbar class="mb-4 p-4">
            <template #start>
                <Button label="新建" icon="pi pi-plus" severity="success" class="mr-2" @click="openNew" />
                <Button label="删除" icon="pi pi-trash" severity="danger" @click="confirmDeleteSelected"
                    :disabled="!selectedProducts || !selectedProducts.length" />
            </template>

            <template #end>
                <FileUpload mode="basic" accept="image/*" :maxFileSize="1000000" label="Import" chooseLabel="Import"
                    class="mr-2 inline-block" />
                <Button label="Export" icon="pi pi-upload" severity="help" @click="exportCSV($event)" />
            </template>
        </Toolbar>

        <DataTable ref="dt" :value="examInfosData" v-model:selection="selectedProducts" dataKey="id" :paginator="true"
            :rows="10" :filters="filters"
            paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown"
            :rowsPerPageOptions="[5, 10, 25]" currentPageReportTemplate="显示 {first} to {last} of {totalRecords} 数据">
            <template #header>
                <div class="flex flex-wrap gap-2 items-center justify-between">
                    <h4 class="m-0">考试管理</h4>
                    <IconField iconPosition="left">
                        <InputIcon>
                            <i class="pi pi-search" />
                        </InputIcon>
                        <InputText v-model="filters['global'].value" placeholder="Search..." />
                    </IconField>
                </div>
            </template>
            <ConfirmDialog class="w-80 h-30"></ConfirmDialog>
            <Column selectionMode="multiple" style="width: 3rem" :exportable="false"></Column>
            <Column field="id" header="id" sortable style="max-width:3rem"></Column>
            <Column field="info" header="名称" sortable style="max-width:10rem"></Column>
            <Column field="status" header="状态" sortable style="max-width:3rem">
                <template #body="slotProps">
                    <Tag :value="slotProps.data.status == 0 ? '公开' : '隐藏'"
                        :severity="getStatusLabel(slotProps.data.status)" />
                </template>
            </Column>
            <Column field="createTime" header="创建时间" sortable style="min-width:16rem">

                <template #body="slotProps">
                    {{ formatDate(slotProps.data.createTime) }}
                </template>

            </Column>
            <Column :exportable="false" style="min-width:8rem">
                <template #body="slotProps">
                    <Button icon="pi pi-pencil" outlined rounded class="mr-2" @click="addExamInfo(slotProps.data)" />
                    <Button icon="pi pi-trash" outlined rounded severity="danger" @click="deleteConfirm" />
                </template>
            </Column>
        </DataTable>
    </div>

    <!-- <Dialog v-model:visible="deleteProductsDialog" :style="{ width: '450px' }" header="删除提醒" :modal="true">
        <div class="confirmation-content">
            <i class="pi pi-exclamation-triangle mr-3" style="font-size: 2rem" />
            <span v-if="examInfo">你确定要删除?</span>
        </div>
        <template #footer>
            <Button label="否" icon="pi pi-times" text @click="deleteProductsDialog = false" />
            <Button label="是" icon="pi pi-check" text @click="deleteSelectedProducts" />
        </template>
    </Dialog> -->


    <!--  新建考试弹框-->
    <Dialog v-model:visible="addExamInfoDialog" modal header="添加考试" :style="{ width: '30rem' }">
        <Divider class="mt-0" />
        <div class="flex align-items-center gap-3 mb-3">
            <label class="font-semibold w-6rem">考试名称</label>
            <InputText v-model="examAddParams.info" class="flex-auto" autocomplete="off" />
        </div>
        <div class="flex align-items-center gap-3 mb-3">
            <label class="font-semibold w-6rem">考试状态</label>
            <div>
                <RadioButton v-model="examAddParams.status" inputId="ingredient1" name="pizza1" :value=0 />
                <label for="ingredient1" class="ml-2">公开</label>&nbsp;&nbsp;
                <RadioButton v-model="examAddParams.status" inputId="ingredient2" name="pizza2" :value=1 />
                <label for="ingredient2" class="ml-2">隐藏</label>
            </div>
        </div>
        <div class="flex justify-content-end gap-2">
            <Button type="button" label="取消" severity="secondary" @click="addExamInfoDialog = false"></Button>
            <Button type="button" label="添加" @click="onSave"></Button>
        </div>
    </Dialog>
</template>
<style scoped lang="scss"></style>